import cv2
import numpy as np

def rect_center_point(outer,inner):
    center_rect=[(outer[0]+inner[0])/2,(outer[3]+inner[1])/2,(outer[2]+inner[2])/2,(outer[1]+inner[3])/2]
    return center_rect

def rectpoints():
    cap = cv2.VideoCapture(0)  # 强制使用 DSHOW 后端  #  强制使用 DSHOW 后端  # 0 表示树莓派摄像头
    width = 320
    height = 240
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
    # 设置摄像头帧率
    fps = 30.0  # 可以设置为 5.0 到 30.0 之间的值
    cap.set(cv2.CAP_PROP_FPS, fps)
    while True:
        ret, frame = cap.read()
        gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        ret, thresh1 = cv2.threshold(gray_img, 43, 255, cv2.THRESH_BINARY_INV)
         # 定义结构元素
        kernel = np.ones((5,5), np.uint8)

        # 闭运算
        closed_image = cv2.morphologyEx(thresh1, cv2.MORPH_CLOSE, kernel)
        # 显示处理后的图像
        # cv2.imshow("opened_image", opened_image)
        # 查找轮廓
        _ ,contours, _ = cv2.findContours(closed_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        # 遍历所有轮廓，寻找嵌套的矩形
        outer_rect = None
        inner_rect = None

        for contour in contours:
            # 计算轮廓的面积
            area = cv2.contourArea(contour)
            # 过滤掉小面积的轮廓
            if area > 1000:  # 根据实际情况调整这个值
                # 近似轮廓
                epsilon = 0.02 * cv2.arcLength(contour, True)
                approx = cv2.approxPolyDP(contour, epsilon, True)

                # 检查轮廓是否为矩形
                if len(approx) == 4:
                    # 计算轮廓的边界框
                    x, y, w, h = cv2.boundingRect(approx)
                    aspect_ratio = float(w) / h

                    # 过滤掉非矩形的轮廓（根据宽高比）
                    if 0.8 < aspect_ratio < 1.2:  # 这个范围可以根据实际情况调整
                        # # 绘制轮廓
                        # cv2.drawContours(frame, [approx], -1, (255), thickness=cv2.FILLED)

                        # 判断是外层还是内层矩形
                        if outer_rect is None or cv2.contourArea(contour) > cv2.contourArea(outer_rect):
                            inner_rect = outer_rect
                            outer_rect = contour
                        elif inner_rect is None or cv2.contourArea(contour) > cv2.contourArea(inner_rect):
                            inner_rect = contour

        # 如果找到内外矩形，输出它们的顶点坐标
        if outer_rect is not None and inner_rect is not None:
            # 近似外层矩形的轮廓
            epsilon_outer = 0.02 * cv2.arcLength(outer_rect, True)
            approx_outer = cv2.approxPolyDP(outer_rect, epsilon_outer, True)
            rect_points_outer = approx_outer.reshape(4, 2)
            # 近似内层矩形的轮廓
            epsilon_inner = 0.02 * cv2.arcLength(inner_rect, True)
            approx_inner = cv2.approxPolyDP(inner_rect, epsilon_inner, True)
            rect_points_inner = approx_inner.reshape(4, 2)

            outer_points = np.array([rect_points_outer[0],rect_points_outer[3],rect_points_outer[2],rect_points_outer[1]], dtype=np.int32)
            inner_points = np.array(rect_points_inner, dtype=np.int32)
            # 绘制外层矩形框
            # 计算中心矩形框的坐标
            points = np.array(rect_center_point(rect_points_outer, rect_points_inner), dtype=np.int32)
            # print("中心矩形框的坐标：", points)
            # 绘制中心矩形框
            # cv2.polylines(frame, [points], isClosed=True, color=(0, 0, 255), thickness=3)
            
            return points,outer_points,inner_points

        if not ret:
            break
        # 显示帧率
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()
